import Vue from 'vue';
import axios from 'axios';
import router from './router.js';
import vm from "../main.js"
let timer = null

// 添加一个请求拦截
axios.interceptors.request.use(function(config) { //config ~~ axios{options}
	// console.log('请求拦截');

	//默认参数
	config.params = config.params || {
		_page: 1,
		_limit: 20
	}
	// config.headers.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QxMjMiLCJfaWQiOiI1ZmU1YTAwZGNmMzI1MjQ3ODRjOTAzNGIiLCJpYXQiOjE2MDg4ODQ5MzgsImV4cCI6MTYwODk3MTMzOH0.TNGfBkAiejyZCeDKb9a8A9ZlbJpfat2FiE3J9339EV0'

	//获取token
	let local = window.localStorage.getItem('user')
	let token = local ? JSON.parse(local).token : ''
	// console.log(token)
	config.headers = {
		token
	}

	clearTimeout(timer)
	timer = setTimeout(() => {
		vm.bLoading = true
	}, 200)

	//显示loading

	return config; //返回配置后的请求
}, function(error) {
	// Do something with request error
	return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function(response) {
	console.log('响应拦截');

	let path = router.currentRoute.fullPath
	console.log(response.data)
	if (response.data.err === 2) { //token校验失败 跳转
		//跳转
		router.replace({
			path: '/login',
			query: {
				backpath: path // 发送当前位置给登录组件
			}
		})
	}

	clearTimeout(timer)
	vm.bLoading = false; //隐藏bLoading

	return response.data; //数据结构简化
}, function(error) {
	// Any status codes that falls outside the range of 2xx cause this function to trigger
	// Do something with response error
	return Promise.reject(error);
});

Vue.prototype.$axios = axios; //未来 vm|组件.$axios
// Vue.prototype.$http=axios;//未来 vm|组件.$axios
// window.axios=axios;//  不推荐
export default axios;
